import { defineStore } from "pinia";
import { showNotify } from "vant";
import router from "@/router";
import { login } from "@/api/user";

export const useUserStore = defineStore("user", {
  persist: {
    paths: ["token", "userid"],
  },

  state() {
    return {
      username: "15200220005", // 用户名
      password: "12345", // 密码

      token: "", // 登录之后的token
      userid: "", // 用户Id
    };
  },

  getters: {
    isDisabled(state) {
      return !state.username || !state.password;
    },
    // 是否登录
    isLogined(state) {
      return state.token;
    },
  },

  actions: {
    /**
     * 登录
     * @param route 当前匹配的路由信息对象 $route
     */
    async submit(route: any) {
      // 调用接口
      const response = await login(this.username, this.password);
      // 登录成功
      this.token = response.data.token;
      this.userid = response.data.userid;

      showNotify({
        type: "success",
        message: "登录成功",
        duration: 1000, // 控制展示时长，默认为 3000 单位是 ms
        onClose: () => {
          // Notify 关闭之后的回调函数

          // 1. 获取url中的 redirect 参数的值
          const redirect = route.query.redirect || "/home";

          // 2. 跳转
          router.replace(redirect);
        },
      });
    },

    /**
     * 退出登录
     */
    async logout() {
      // 1. 清空本地存储
      localStorage.clear();
      // 2. 清除 token 与 useid
      this.token = "";
      this.userid = "";
      // 3. 跳转到首页
      router.replace({ name: "home" });
    },
  },
});
